/*
   Copyright 2011 James Bowling

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.armedia.dctm.constraints.test;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.IDfLoginInfo;

public class SessionFactory {
	
	public enum ParamName {
		docbase,
		username,
		password
	}
	
	private static SessionFactory singleton;
	
	private SessionFactory() {
		
	}
	
	public static synchronized SessionFactory getInstance() {
		if (singleton == null) {
			singleton = new SessionFactory();
		}
		return singleton;
	}
	
	public IDfSession getSession() throws Exception {
		String docbase = System.getProperty(ParamName.docbase.toString());		
		String username = System.getProperty(ParamName.username.toString());
		String password = System.getProperty(ParamName.password.toString());
		IDfSessionManager sessionManager = createSessionManager(docbase, username, password);
		return sessionManager.getSession(docbase);
	}
	
    static IDfSessionManager createSessionManager(String docbase, String username, String password) throws Exception {
        //create Client objects
        IDfClientX clientx = new DfClientX();
        IDfClient client = clientx.getLocalClient();
        
        //create a Session Manager object
        IDfSessionManager sMgr = client.newSessionManager();
        
        //create an IDfLoginInfo object named loginInfoObj
        IDfLoginInfo loginInfoObj = clientx.getLoginInfo();
        loginInfoObj.setUser(username);
        loginInfoObj.setPassword(password);
        loginInfoObj.setDomain(null);
        
        //bind the Session Manager to the login info
        sMgr.setIdentity(docbase, loginInfoObj);

        return sMgr;
    }	

}
